import updateManager from './common/updateManager';
const systemHelper = require('./common/system-helper');
const sspUserService = require('./services/ssp-user-service');
const messages = require('./common/messages');

App({
  globalData: {
    userInfo: null,
    token: null,
  },
  onLaunch: function () {
    // wx.navigateTo({ url: `/pages/login/index` });
    // 检查本地存储中是否有登录信息
    // const userInfo = wx.getStorageSync('userInfo');
    // const token = wx.getStorageSync('token');
    // const expireTime = wx.getStorageSync('expireTime');
    // if (userInfo && token && expireTime && expireTime > Date.now() + 24 * 60 * 60 * 1000) {
    //   // 如果登录信息未过期，直接使用
    //   this.globalData.userInfo = userInfo;
    //   this.globalData.token = token;
    // } else {
    //   this.login();
    // }
  },
  login: function () {
    systemHelper
      .login()
      .then((res) => sspUserService.login(res.code))
      .then((res) => {
        if (res.statusCode !== 200) {
          throw '登录失败';
        }
        // 登录成功，保存token和用户信息
        const { token, userInfo, expireTime } = res.data;
        wx.setStorageSync('token', token);
        wx.setStorageSync('userInfo', userInfo);
        wx.setStorageSync('expireTime', expireTime);

        this.globalData.userInfo = userInfo;
        this.globalData.token = token;
        messages.showMessage('登录成功');
      })
      .catch(messages.showError);
  },
  onShow: function () {
    updateManager();
  },
});
